import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [
      
      {
        name: '诸葛亮',
        price: 1000,
        num: 1, // num购物车数量
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },{  "name": "鲁班", "price": 2200, "num": 1, "checked": true }],
  },
  mutations: {
    // 数量
    handleChange (state,obj) {
      state.list.filter(item => item.id == obj.id).num = obj.num
    },
    // 列表数据
    saveList (state,val) {
      state.list = val
    },
    // 单个复选框事件
    cbChange (state, obj) {
      state.list.filter(item => item.id == obj.id).checked = obj.checked
    },
    // 全选事件
    cbaChange (state, status) {
      state.list.forEach(item=>item.checked = status)
    },
    // 总价
    amountAll (state, val) {
      state.t = val
    },


    addCount (list, index1) { // 这里第一个形参goodlist要写计算加减的数据固定写法
      console.log('addcount 的輸入:', index1)
      const rec = this.state.list[index1]// rec接收索引值 去goodlist的第一个索引值，通过索引值来加减
      // console.log(item1)
      rec.num++
    },
    redCount (list, index1) {
      console.log('addcount 的輸入:', index1)
      const rec = this.state.list[index1]
      // console.log(item1)
      // rec.num--
      if (rec.num <= 1) { // 通过索引减到0后不减
        // this.num = 0
        rec.num = 1
      } else {
        // this.num--
        rec.num--
      }
    },

    delCount (list, index1) {
      // const rec = this.state.goodList[index2]
      this.state.list.splice(index1, 1)
    }


  },
  actions: {
    // async getList (context) {
    //  const {data:res} = await axios.get('https://www.escook.cn/api/cart')
    //   console.log(res.list);
    //   context.commit('saveList',res.list)
    // }
  },
  modules: {
  },
  getters: {
    // 监听全选框发生变化
    checkAll (state) {
      if (state.list.every(item => item.checked)) {
        return true
      } else {
        return false
      }
    },
    // 已选选中按钮的总价格
    amountAll (state) {
      let t = 0
      if (state.list.some(item => item.checked)) {
        const list = state.list.filter(item => item.checked)
        list.forEach(item => {
          t += item.num*item.price
        })
        return t
      } else {
        return t
      }
    },
    // 勾选的商品数量
    countAll (state) {
      let n = 0
      state.list.filter(item => item.num).forEach(item => {
        return n += item.num
      })
      return n
      
    }

    // 
  }
})
